package com.shujia.spark.stream

import java.text.SimpleDateFormat
import java.util.Date

import com.alibaba.fastjson.{JSON, JSONObject}
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.{Durations, StreamingContext}
import org.apache.spark.{SparkConf, SparkContext}
import redis.clients.jedis.Jedis

object Demo9RoadFlow {
  def main(args: Array[String]): Unit = {
    /**
      * 统计每个道路车流程，统计最近15秒，每隔5秒统计一次
      *
      */

    val conf = new SparkConf()
    conf.setMaster("local[2]")
    conf.setAppName("road")

    val sc = new SparkContext(conf)

    val ssc = new StreamingContext(sc, Durations.seconds(5))

    ssc.checkpoint("data/checkpoint")


    val kafkaParams: Map[String, Object] = Map[String, Object](
      ///kafka集群列表
      "bootstrap.servers" -> "master:9092,node1:9092,node2:9092",
      //key value的反序列化的类
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      //消费者组
      "group.id" -> "asdasdasdasd",
      //读取数据的位置 latest: 读取最新的数据， earliest：读取所有的数据
      "auto.offset.reset" -> "latest",
      //是否开启自动提交消费便宜量，消费便宜量默认保存至zookeeper
      "enable.auto.commit" -> "true"
    )

    val topics = Array("cars")

    //基于kafka创建DStream
    val kafkaDStream: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )
    //取出value
    val carsDS: DStream[String] = kafkaDStream.map(_.value())

    //取出道路编号
    val kvDS: DStream[(Long, Int)] = carsDS.map(car => {
      val jsonObj: JSONObject = JSON.parseObject(car)
      val roadId: Long = jsonObj.getLong("road_id")
      (roadId, 1)
    })

    //实时统计道路的车流量
    val raodFlowDS: DStream[(Long, Int)] = kvDS.reduceByKeyAndWindow(
      (x: Int, y: Int) => x + y,
      (i: Int, j: Int) => i - j,
      Durations.seconds(15),
      Durations.seconds(5)
    )

    val filterDS: DStream[(Long, Int)] = raodFlowDS.filter(_._2 != 0)


    /**
      * 将数据保存到redis中
      *
      */

    filterDS.foreachRDD(rdd => {
      rdd.foreachPartition(iter => {

        //1、建立redis链接
        val jedis = new Jedis("master", 6379)

        iter.foreach {
          case (roadId: Long, flow: Int) =>
            val date: Date = new Date()
            val format = new SimpleDateFormat("yyyyMMddhhmmss")
            val dateStr: String = format.format(date)
            //以道路编号和时间作为key
            val key: String = roadId + ":" + dateStr

            //将火速写入redis
            jedis.set(key, flow.toString)

            //设置过期时间
            jedis.pexpire(key, 60000)
        }

        //关闭链接
        jedis.close()
      })

    })

    ssc.start()
    ssc.awaitTermination()
    ssc.stop()

  }
}
